{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torchvision.datasets as datasets\n",
    "import torchvision.transforms as transforms"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 加载数据集（使用你的数据路径）\n",
    "data_path = \"./data/MNIST\"\n",
    "transform = transforms.Compose([\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize((0.1307,), (0.3081,))\n",
    "])\n",
    "\n",
    "train_dataset = datasets.MNIST(\n",
    "    data_path, train=True, download=False, transform=transform\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "前5个样本的标签（原始格式）：\n",
      "样本1的标签：5，类型：<class 'int'>，形状：标量\n",
      "样本2的标签：0，类型：<class 'int'>，形状：标量\n",
      "样本3的标签：4，类型：<class 'int'>，形状：标量\n",
      "样本4的标签：1，类型：<class 'int'>，形状：标量\n",
      "样本5的标签：9，类型：<class 'int'>，形状：标量\n"
     ]
    }
   ],
   "source": [
    "# 方法1：直接查看数据集的标签（取前5个样本）\n",
    "print(\"前5个样本的标签（原始格式）：\")\n",
    "for i in range(5):\n",
    "    image, label = train_dataset[i]  # 每个样本是(图像, 标签)元组\n",
    "    print(f\"样本{i+1}的标签：{label}，类型：{type(label)}，形状：{label.shape if hasattr(label, 'shape') else '标量'}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "批量标签（DataLoader获取）：\n",
      "标签值： tensor([5, 0, 4, 1, 9])\n",
      "标签形状： torch.Size([5])\n"
     ]
    }
   ],
   "source": [
    "# 方法2：通过DataLoader查看批量标签\n",
    "from torch.utils.data import DataLoader\n",
    "train_loader = DataLoader(train_dataset, batch_size=5, shuffle=False)\n",
    "batch_images, batch_labels = next(iter(train_loader))  # 获取第一个批次\n",
    "print(\"\\n批量标签（DataLoader获取）：\")\n",
    "print(\"标签值：\", batch_labels)\n",
    "print(\"标签形状：\", batch_labels.shape)  # 若为One-hot编码，形状应为[batch_size, 10]\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "science39",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
